package com.sihan.swvp.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sihan.swvp.common.IpUtil;
import com.sihan.swvp.entity.sys.User;
import com.sihan.swvp.service.sys.LogService;

@Component("powerFilter")
public class PowerFilter {

	@Autowired
	public LogService logService;

    public void filter(ServletRequest req,ServletResponse res) throws IOException{ /*具体实现过滤器方法*/
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI();
		String context = request.getContextPath();
		boolean filter = context.equals("/" + uri.replace("/", ""))
				|| uri.contains(".do");
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("u");
		if(user != null && filter && user != null && user.getId() != 0 && filter && !uri.endsWith("login.jsp") && !uri.endsWith("login.do")
				&& !uri.endsWith("getVimg.do") && !uri.contains("getVideoPic.do") && !uri.contains("update")
				&& !uri.contains("delete") && !uri.contains("save") && !uri.contains("add") && !uri.contains("set")
				&& !uri.contains("login")&& !uri.contains("getImg")&& !uri.contains("changePwd")
				&& !uri.contains("login")&& !uri.contains("getUserLoginCount")&& !uri.contains("selectUserByAccount")&& !uri.contains("getWgSyjsList")
				&& !uri.contains("getGsggList")&& !uri.contains("getImgs")&& !uri.contains("getNavigationMenu")&& !uri.contains("getMenu")
				&& !uri.contains("getConfig")&& !uri.contains("logout")&& !uri.contains("getWgBj")
				){
			
			List<Map<String, Object>> menulist = (List<Map<String, Object>>) session.getAttribute("menu");
			List<String> stringList = new ArrayList<String>();
			for(int i=0;i<menulist.size();i++){
				String menuUrl = (String) menulist.get(i).get("menuurl");
				if(menuUrl.contains(",")){
					String[] urls = menuUrl.split(",");
					for(String s : urls){
						stringList.add(s);
					}
				}
				stringList.add(menuUrl);
			}
			int count = 0;
			for(String url : stringList){
				if(uri.contains(url)){
					count++;
				}
			}
			if(count <= 0){
				logService.addUserLog("越权访问", "权限", user.getId(), "用户："+user.getName()+"越权访问",IpUtil.getLocalIp(request),0,1);
				response.sendError(500, "超出你的访问权限");
			}
		}
	}
}
